#define _CRT_SECURE_NO_WARNINGS

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        int n = fruits.size();
        vector<int> harsh(n + 1, 0);
        int ret = 0, cnt = 0;

        for (int left = 0, right = 0; right < fruits.size(); right++)
        {
            if (harsh[fruits[right]] == 0)
                cnt++;

            harsh[fruits[right]]++;

            while (cnt > 2)
            {
                harsh[fruits[left++]]--;
                if (harsh[fruits[left - 1]] == 0)
                    cnt--;
            }
            ret = max(ret, right - left + 1);
        }

        return ret;
    }
};